package com.xgkj.diyiketang.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xgkj.diyiketang.ProtocolConst;
import com.xgkj.diyiketang.data.MessageInfo;
import com.xgkj.diyiketang.http.CouponHttpRequest;
import com.xgkj.diyiketang.http.CouponHttpResponse;
import com.xgkj.diyiketang.http.engine.CouponHttpBaseTask;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrater on 2015/12/8.
 */
public class SysMsgListTask extends CouponHttpBaseTask {
    private int mSize;
    private int mPageNo;
    private static final String SYSMSGLISTJSON = "sysMsgList";

    public SysMsgListTask(int size, int pageNo) {
        super(TaskType.GET_SYSMSG_LIST_TASK);
        mSize = size;
        mPageNo = pageNo;
    }

    @Override
    protected void processResponseData(CouponHttpResponse response) {

            JSONObject json = response.getBody();
            int currentPage = 0;
            int pageCount = 0;
            int nextPage = 0;
            List<MessageInfo> list = new ArrayList<MessageInfo>();
            if (json != null) {
                JSONObject jsonString = json.getJSONObject("sysMsgList");
                if (jsonString != null) {
                    currentPage = jsonString
                            .getIntValue(ProtocolConst.CURRENT_PAGE);
                    pageCount = jsonString.getIntValue(ProtocolConst.PAGE_COUNT);
                    nextPage = currentPage >= pageCount ? 0 : (currentPage + 1);
                    list = JSON.parseArray(
                            jsonString.getString(ProtocolConst.LIST_TAG),
                            MessageInfo.class);
                }

            }
            notifyTaskCompleted(nextPage, list);

    }

    @Override
    protected void prepareRequest() {
        super.prepareRequest();
        if (mPhase == TASK_PHASE_INIT) {
            CouponHttpRequest request = new CouponHttpRequest(
                    RequestType.GET_SYSMSG_LIST_REQUEST);
            JSONObject json = new JSONObject();
            json.put("size", mSize);
            json.put("pageNo", mPageNo);
            request.setData(json.toString());
            request.setApiNo(ApiNo.GET_SYSMSG_LIST);
            addRequest(request);
        }
    }
}
